package priv.lhy.ecm.collectorConsumer.nettyServer;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import priv.lhy.common.constants.RedisConstant;
import priv.lhy.ecm.datadispose.IDispose;

/**
 * author: lihy
 * date: 2019/6/18 10:31
 * description:
 */
@Component
@Qualifier("serverHandler")
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {

    @Value("${netty.delimiter}")
    private String delimiter;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IDispose dispose;

    private final static Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        LOGGER.info("接受信息：" + msg);
        String[] message = msg.split("\\|");

        String result;
        if (redisTemplate.opsForSet().isMember(RedisConstant.COLLECTOR_TOKEN, message[0])) {
            //合法数据
            result = dispose.disposeLegalData(message);
        } else {
            //非法数据
            result = dispose.disposeIllegalData(ctx.channel().localAddress().toString());
        }

        ctx.channel().writeAndFlush(result + delimiter);
        ctx.channel().close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }
}
